package com.sky;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

//————————————————
//版权声明：本文为CSDN博主「ynerz」的原创文章，遵循CC 4.0 BY-SA版权协议，转载请附上原文出处链接及本声明。
//原文链接：https://blog.csdn.net/qq_49721258/article/details/141605693

@SpringBootApplication
@EnableTransactionManagement //开启注解方式的事务管理
@Slf4j
public class SkyApplication {
    public static void findProcessOnPort(int port) {
        String netstatCommand = "netstat -ano | findstr :" + port;
        String pid = "";
        try {
            // 执行netstat命令获取占用指定端口的进程ID
            ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe", "/c", netstatCommand);
            Process process = processBuilder.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

            String line;
            while ((line = reader.readLine()) != null) {
                if (line.contains("LISTENING")) {
                    String[] parts = line.trim().split("\\s+");
                    pid = parts[parts.length - 1]; // 进程ID是最后一部分

                    System.out.println("Found process on port " + port + " with PID: " + pid);
                }
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        killProcess(pid);
    }

//————————————————
//    版权声明：本文为CSDN博主「ynerz」的原创文章，遵循CC 4.0 BY-SA版权协议，转载请附上原文出处链接及本声明。
//    原文链接：https://blog.csdn.net/qq_49721258/article/details/141605693
    public static boolean killProcess(String pid) {
        String taskkillCommand = "taskkill /PID " + pid + " /F";

        try {
            // 执行taskkill命令关闭进程
            ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe", "/c", taskkillCommand);
            Process process = processBuilder.start();
            process.waitFor();
            System.out.println(true);
            return true;
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(false);
        return false;
    }
//————————————————
//    版权声明：本文为CSDN博主「ynerz」的原创文章，遵循CC 4.0 BY-SA版权协议，转载请附上原文出处链接及本声明。
//    原文链接：https://blog.csdn.net/qq_49721258/article/details/141605693
    public static void main(String[] args) {
        SpringApplication.run(SkyApplication.class, args);
        log.info("server started");
    }
}
